package com.ruoyi.util.http;

import java.io.IOException;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * @Description: 使用pstmain, 的 form-data 发送参数.,请求类型为post
 *
 * @ClassName: FromDataHttp
 * @author syc
 * @date: 2022年9月14日 上午11:47:32
 */
public class FromDataHttp {
	/**
	 *	是2022-09-14遇到这个问题的,
	 */
	
	
	/**
     * 	以post方式调用第三方接口,以form-data 形式  发送数据
     * https://blog.csdn.net/LYY1448019681/article/details/115124407
     * @param url  post请求url
     * @param paramMap 表单里其他参数
     * @return
     */
    public static String doPost(String url, Map<String, String> paramMap) {
        // 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);       
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);       
            //表单中参数
           for(Map.Entry<String, String> entry: paramMap.entrySet()) {
                builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }    
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交
                      
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            }      
        } catch (Exception e) {
            e.printStackTrace();
           // logger.error("调用HttpPost失败！" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                   // logger.error("关闭HttpPost连接失败！");
                }
            }
        }       
        return null;              
    }
}
